﻿using Common.Cache;
using Common.MefHelp.Attributes;
using Common.Tools;
using Common.Tools.Model;

namespace Common.Algorithm
{
    /// <summary>
    /// 最佳资源获取
    /// </summary>
    [CustomInjection]
    public class BestResources
    {
        /// <summary>
        /// 缓存使用
        /// </summary>
        private readonly ICustomCache _customCache;
        /// <summary>
        /// 构造函数
        /// </summary>
        public BestResources(ICustomCache customCache)
        {
            _customCache = customCache;
        }
        /// <summary>
        /// 获取最佳机器
        /// </summary>
        /// <param name="services">所有服务</param>
        /// <returns></returns>
        public async Task<IpAndPort?> GetHost(List<IpAndPort> services)
        {
            if (services == null || services.Count <= 0)
            {
                return null;
            }
            try
            {
                //获取缓存的服务数据
                var allService = new List<SelfDetail>();
                foreach (var service in services)
                {
                    var self = await _customCache.GetAsync<SelfDetail>(service.ToString());
                    if (self == null) continue;
                    allService.Add(self);
                }
                if (allService.Count == 0) return null;
                //找到站的数量最少的那个
                return allService.OrderBy(x => x.StationNum).Select(g => new IpAndPort
                {
                    Ip = g.Ip,
                    Port = g.Port,
                }).First();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return null;
            }
        }
    }
}
